<?php

namespace app\admin\controller\test\zym;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\TestZymAnswer;
use app\admin\model\test\zym\Cate as zymCate;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Answer extends Backend
{
    
    /**
     * Answer模型对象
     * @var \app\admin\model\test\zym\Answer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\test\zym\Answer;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function info($ids = null){
        $cates = zymCate::all();
        $row = TestZymAnswer::get($ids);

        if(!$row){
            $this -> redirect('zymtest');
        }
        $answers_ana = unserialize($row->answers_ana);
        $assData = [
            'cates' => $cates,
            'answers_ana'   => $answers_ana
        ];
        if($row -> imgs){
            $img = unserialize($row -> imgs);
            $this -> assign('img',$img);
        }
        $this -> assign('assData',$assData);
        return $this -> fetch();
    }

    public function download($ids = null){
        $cates = zymCate::all();
        $row = TestZymAnswer::get($ids);

        if(!$row){
            $this -> redirect('zymtest');
        }
        $answers_ana = unserialize($row->answers_ana);
        $assData = [
            'cates' => $cates,
            'answers_ana'   => $answers_ana
        ];
        if($row -> imgs){
            $img = unserialize($row -> imgs);
            $this -> assign('img',$img);
        }

        $languageEnGb = new \PhpOffice\PhpWord\Style\Language(\PhpOffice\PhpWord\Style\Language::ZH_CN);

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $phpWord->getSettings()->setThemeFontLang($languageEnGb);

		$sectionX = $phpWord->addSection([
		      'pageSizeH' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(12.7),
		      'pageSizeW' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(8.3)
		]);
		$imgUrl = ROOT_PATH.'public/assets/img/water1.png'; //获取封面URL地址
		$botImgUrl = ROOT_PATH.'public/assets/img/water4.png';
		
//		$sectionX->addImage(
//		    $imgUrl,
//		    array(
//		        'width' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(2.677)),
//		        'height' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.177)),
//		        'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//			   'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//			   'posVertical' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//			   'marginRight' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//			   'marginTop' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//			   'wrappingStyle' => 'infront'
//		    )
//		);
//		$sectionX->addImage(
//		    $botImgUrl,
//		    array(
//		       'width' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(16)),
//		       'height' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(7.6)),
//		        'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//		        'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER,
//		        'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
//		        'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
//		        'marginRight' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//		        'marginBottom' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//		        'posVertical'      => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_BOTTOM,
//		    )
//		);
		//标题
		$sectionX-> addText('测评报告',
		   [
		           'size'    => 60,
		           'bold' => true,
		           'name'=>'黑体',
		           'color'=>'#0674bc',
		       ],[
		           'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
		           'spaceAfter'  => 0,                                                   //标题后部预留长度
		           'spaceBefore' => 3550,                                                    //标题前部预留长度
		       ]
		);
		$sectionX-> addText('Talent Evaluation Report',
		   [
		           'size'    => 20,
		           'bold' => false,
		           'name'=>'黑体',
		           'color'=>'#0674bc',
		       ],[
		           'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
		           'spaceAfter'  => 0,                                                   //标题后部预留长度
		           'spaceBefore' => 70,                                                    //标题前部预留长度
		       ]
		);
        $section = $phpWord->addSection([
            	'pageSizeH' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(12.7),
            	'pageSizeW' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(8.3)
        ]);
        $paragraphStyleName = 'pStyle';
        $phpWord->addParagraphStyle($paragraphStyleName, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,'spaceAfter' => 300,'spaceBefore' => 500));
        $fontStyleName = 'rStyle';
        $phpWord->addFontStyle($fontStyleName, array('name'=>'黑体', 'size' => 16, 'allCaps' => true));
        $section -> addText('职业锚测评',[
                'size'    => 18,
                'bold' => true,
                'name'=>'黑体',
                'color'=>'black'
            ],[
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
                'spaceAfter'  => 500,                                                   //标题后部预留长度
                'spaceBefore' => 500,                                                    //标题前部预留长度
            ]);



        if(isset($img)){
            $imgcount = count($img);
            foreach ($img as $ig){
                $imgpath = $_SERVER['DOCUMENT_ROOT'].$ig;
                if(!is_file($imgpath)) continue;
                $info = getimagesize($imgpath);
                $oheight = $height = $info[1];
                $owidth = $width = $info[0];
                if($imgcount == 1){
                    $width = min($width,300);
                    $height = intval($oheight * ($width/$owidth));
                }
                $section->addImage($_SERVER['DOCUMENT_ROOT'].$ig, array('width'=>$width, 'height'=>$height,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER));
            }
        }



        // $section -> addText('职业锚测试得分',$fontStyleName, $paragraphStyleName);


        $str1 = ['成绩'];
        $str2 = ['得分'];
        $ana = [];
        $strong = '';
        $nomal = '';
        $weak = '';
        foreach($assData['cates'] as $k => $v){
            $str1[] = $v['name'];
            $str2[] = $assData['answers_ana'][$v['id']];
            $ana[$v['id']] = [
                'name'  => $v['name'],
                'score' => $assData['answers_ana'][$v['id']]
            ];
            if($assData['answers_ana'][$v['id']] > 16){
                $strong .= $v['name'].',';
            }elseif($assData['answers_ana'][$v['id']] > 8 && $assData['answers_ana'][$v['id']] <=16){
                $nomal .= $v['name'].',';
            }else{
                $weak .= $v['name'].',';
            }
        }


        // $section->addTextBreak(1);
        $fancyTableStyleName = 'Fancy Table';
        $fancyTableStyle = array('borderSize' => 1, 'borderColor' => '000000', 'cellMargin' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER, 'cellSpacing' => 0);
        $fancyTableFirstRowStyle = array('borderBottomSize' => 18, 'borderBottomColor' => '000000', 'bgColor' => '000000');
        $fancyTableCellStyle = array('valign' => 'center');
        $fancyTableFontStyle = array('bold' => true);
        $phpWord->addTableStyle($fancyTableStyleName, $fancyTableStyle, $fancyTableFirstRowStyle);
        $table = $section->addTable($fancyTableStyleName);


        // for ($r = 1; $r <= 2; $r++) {
        //     $table->addRow();
        //     if($r == 1){
        //         foreach ($str1 as $v){
        //             $table->addCell(1050, $fancyTableCellStyle)->addText($v, $fancyTableFontStyle);
        //         }
        //     }
        //     if($r == 2){
        //         foreach ($str2 as $v){
        //             $table->addCell(1050)->addText($v);
        //         }
        //     }
        // }


        $section -> addText('职业倾向测评分析详解',[
                'size'    => 16,
                'name'=>'黑体',
                'color'=>'black'
            ],[
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
                'spaceAfter'  => 500,                                                   //标题后部预留长度
                'spaceBefore' => 300,                                                    //标题前部预留长度
            ]);
        $table = $section->addTable($fancyTableStyleName);
        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("类型");
        $table->addCell(7400, $fancyTableCellStyle)->addText("详解");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("技术型（TF）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("愿意展示自己的技能，并不断提升自己的技术，发挥更为专业的能力。希望通过施展自己的技能以获取别人认可，并乐于接受来自于专业领域的挑战。");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("管理型（GM）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("追求组织中的管理职位，喜欢发号施令，领导众人，因此能够整合其他人的工作，并对组织中某项工作的绩效承担责任。");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("自主型（AU）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("希望可以按照自己的方式工作和生活，总能提供足够的灵活性，无法忍受公司种种的约束，追求无拘无束。");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("安全型（SE）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("喜欢稳定的职位，更为强调财务安全和就业安全，关注五险一金、养老金以及税收。对组织忠心耿耿，可以长久地从事某一行业。");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("创造型（EC）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("冒险能力强，手腕强硬，希望向周围的人证明你有能力创建一家企业，并且能够全方位的学习，以此来实现自己的创业计划。");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("服务型（SV）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("追求职业的价值取向，希望可以做一些利于他人的事，例如教育、环保、公益、慈善等。富有爱心，安全感和同情心。");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("挑战型（CH）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("总是跃跃欲试，希望战胜强硬的对手和克服面临的困难。多层次的、复杂的情况对你来说是一剂强心针，厌倦简单及重复的工作。");

        $table->addRow(600);
        $table->addCell(2050, $fancyTableCellStyle)->addText("生活型（LS）");
        $table->addCell(7400, $fancyTableCellStyle)->addText("家庭的需求和你个人的休息对你来说非常重要，因此你希望职业有足够的弹性，能让你平衡并整合个人的、家庭的和职业的矛盾，并且让他们协调统一地共同发展。");


        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');


        $user = User::get($row -> user_id);
        $file_name = 'uploads/ZYM-'.$user['mobile'].'-'.(rand(1111,9999)).'.docx';

        $objWriter->save($file_name);


        //以只读和二进制模式打开文件
        $file = fopen ( $file_name, "rb" );

        //告诉浏览器这是一个文件流格式的文件
        Header ( "Content-type: application/octet-stream" );
        //请求范围的度量单位
        Header ( "Accept-Ranges: bytes" );
        //Content-Length是指定包含于请求或响应中数据的字节长度
        Header ( "Accept-Length: " . filesize ( $file_name ) );
        //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
        Header ( "Content-Disposition: attachment; filename=" . 'ZYM-'.$user['nickname'].'-'.(rand(1111,9999)).'.docx' );

        //读取文件内容并直接输出到浏览器
        echo fread ( $file, filesize ( $file_name ) );
        fclose ( $file );
        exit ();
    }

}
